<template>
  <a-config-provider prefix-cls="ss">
    <a-spin
      style="margin-top: 15%"
      size="large"
      :tip="tipText"
      :spinning="loading"
    >
      <div class="container">
        <!-- 创意混剪项目头部 -->
        <navBack
          :leftConfig="{
            isShow: true,
          }"
          :contentConfig="{
            isShow: true,
          }"
          :rightConfig="{
            isShow: true,
          }"
          @backClick="backClick"
        >
          <!-- 头部左侧文字 -->
          <!-- <template #left_text>
            <span
              v-if="VideoMashup.id !== 0"
              @click="backClick"
              style="
                font-size: 12px;
                margin-left: 15px;
                font-weight: lighter;
                cursor: pointer;
              "
            >
              <cu-icon
                type="icon-baocunchenggong"
                style="font-size: 14px"
              ></cu-icon>
              已保存</span
            >

            <span
              v-else
              @click="backClick"
              style="
                font-size: 12px;
                margin-left: 15px;
                font-weight: lighter;
                cursor: pointer;
              "
            >
              <close-circle-filled style="font-size: 14px; color: red" />
              暂未保存</span
            >
          </template> -->
          <!-- 头部中间可编辑文本 -->
          <template #content_text>
            <EditableHead
              :titleText="titleText"
              @changeTitle="titleText = $event"
            ></EditableHead>
            <!-- 原本的页面 -->
          </template>
          <template #right_btns>
            <div class="right_btns">
              <!-- {{ queryData.id + 'ididi' }} -->
              <!-- 保存为官方模板按钮 -->
              <a-button
                @click="saveTemplateHandle('officialTemplate')"
                v-if="
                  isShowTitleBtn.OfficialTemplate.show &&
                  clipRole.includes('create_official_template')
                "
                style="margin-right: 10px"
              >
                {{ isShowTitleBtn.OfficialTemplate.text }}
              </a-button>
              <!-- 保存为我的模板按钮 -->
              <a-button
                v-if="isShowTitleBtn.MyTemplate.show"
                @click="saveTemplateHandle('baseTemplate')"
              >
                {{ isShowTitleBtn.MyTemplate.text }}
              </a-button>
              <!-- 保存混剪项目 -->
              <a-button
                v-if="isShowTitleBtn.saveMontage.show"
                @click="saveTemplateHandle('mixedShear')"
                >{{ isShowTitleBtn.saveMontage.text }}</a-button
              >
              <!-- TODO 新人引导 待开发 -->
              <!-- <div class="guide_box">
                  <cu-icon type="icon-xinshourumen"> </cu-icon>
                  <span>新人引导体验</span>
                </div> -->
              <!--  混剪预览 -->
              <a-button
                v-if="isShowTitleBtn.preview.show"
                style="font-size: 13px; border-radius: 5px"
                type="primary"
                @click="previewHandle"
                :loading="previewHandleLoding"
                >{{ isShowTitleBtn.preview.text }}
              </a-button>
              <!-- :disabled="!allVideoGroup"  -->
            </div>
          </template>
        </navBack>
        <!-- TODO  加载时滚动条失效 <a-spin tip="加载中..." :spinning="loading"> -->
        <!-- 创意混剪项目内容区域 -->
        <div class="content">
          <div class="content-box">
            <div class="content-lf">
              <div class="content-lf-header">
                <div class="lf-header-title">
                  <h3 style="font-weight: 600">镜头内容与配置</h3>
                  <p>为各个镜头配置素材、文案、时长等信息</p>
                </div>
                <div class="lf-header-btn-group">
                  <!-- AI配图 -->
                  <!-- <div class="ai_plot" v-if="queryData.viewType == 2">
                    <a-switch :checkedValue="1" :unCheckedValue="2" v-model:checked="ai_mapping" size="mini" />
                    <PlotDialog ref="PlotDialogRef" :aiModelList="aiModelList">
                      <template #trigger>
                        <div style="padding-top: 1px" @click="PlotDialogRef.openPop">
                          <a-button type="link" style="padding: 0; height: 22px;">AI配图</a-button>
                        </div>
                      </template>
                    </PlotDialog>
                  </div> -->

                  <a-button
                    size="small"
                    :loading="iconLoading"
                    @click="AIWritingAssistantHandle"
                    style="display: flex; align-items: center"
                  >
                    <template #icon>
                      <cu-icon
                        type="icon-AIxiezuozhushou"
                        style="color: #2580fd; font-size: 18px; margin-top: 3px"
                      ></cu-icon>
                    </template>
                    AI写作助手
                  </a-button>
                  <a-button
                    @click="authoringScriptHandle('mixedCutCreat')"
                    size="small"
                    style="margin: 0 5px"
                    ><vertical-align-bottom-outlined />导入脚本
                  </a-button>
                </div>
              </div>
              <!-- v-model="VideoMashup.resource_data" key="id" -->
              <div class="videoGroupCard_box" id="videoGroupCard_box">
                <Draggable
                  :animation="200"
                  class="video_preview_content"
                  key="id"
                  v-model="VideoMashup.resource_data"
                  :forceFallback="true"
                  :scrollSensitivity="100"
                  :scrollSpeed="20"
                  handle=".tongs"
                  :emptyInsertThreshold="5"
                  :bubbleScroll="false"
                  direction="vertical"
                >
                  <template #item="{ element, index }">
                    <videoGroupCard
                      :key="element.id"
                      @openSubtitledubbingDrawer="openSubtitledubbingDrawer"
                      @openSettitleDrawer="openSettitleDrawer"
                      @updateName="updateName($event, element)"
                      @openAicreateImg="openAicreateImg"
                      :targetIndex="index"
                      :itemData="{ ...element }"
                      :explableData="explableData"
                      :ai_requestData="ai_requestData"
                    >
                      <template #default>
                        <div class="tongs" id="tongs">
                          <HolderOutlined />
                        </div>
                      </template>
                    </videoGroupCard>
                  </template>
                </Draggable>
                <a-button
                  size="large"
                  style="width: 100%; margin-bottom: 54px; font-size: 13px"
                  @click="addVideoGroupHandle"
                  ><plus-outlined />新增镜头组</a-button
                >
              </div>
            </div>

            <div class="content-middle">
              <div class="content-middle-title">
                <h3 style="font-weight: 600">视频配置</h3>
                <p>为整体效果进行统一配置</p>
              </div>
              <div class="content-middle-context">
                <videoConfiguration
                  :globalLabel="globalLabel"
                  @openGlobalT="openGlobalT"
                  @openGlobalSubtitledubbingDrawer="
                    openGlobalSubtitledubbingDrawer
                  "
                />
              </div>
            </div>
            <div class="content-rg">
              <div class="content-rg-title">
                <h3 style="font-weight: 600">
                  配置预览
                  <a-tooltip>
                    <template #title>
                      这是结合配置模拟的效果，暂未涉及混剪&智能算法，请点击「视频混剪预览」，生成更贴近成片的预览
                    </template>
                    <exclamation-circle-outlined
                      style="margin-left: 3px; color: #737a87"
                    />
                  </a-tooltip>
                </h3>
                <p style="color: #737a87">查看配置效果</p>
              </div>
              <div class="content-rg-context">
                <videoSimulation :queryData="queryData" />
              </div>
            </div>
          </div>
        </div>

        <AuthoringScript ref="authoringScript" @importScript="importScript" />
        <AIWritingAssistant ref="aiWritingAssistant" />
        <!-- 字幕与配音抽屉 -->
        <SubtitledubbingDrawer
          ref="subtitledubbingDrawer"
          @openUpLoad="openUpLoad"
          :title="title_name"
        />
        <!-- 文字标题抽屉 -->
        <LiteralTitleDrawer
          ref="literalTitleDrawerComponent"
        ></LiteralTitleDrawer>
        <!-- 全局文字标题抽屉 -->
        <GlobalTitleDrawers
          @GlobTitleState="GlobTitleState"
          ref="GloballedubbingDrawer"
        ></GlobalTitleDrawers>
        <NewGuidExperience ref="newGuidExperience" />
        <!-- 此组件发起的页面跳转不拦截 -->
        <saveTemplate ref="savetemplate" :type="queryData" />
        <!-- 全局字幕与配音抽屉 -->
        <GlobalSubtitledubbingDrawer ref="globalSubtitledubbingDrawer" />
        <!-- 选择音频上传 -->
        <ChooseMaterial
          :isClip="false"
          material_type="audio"
          :visible="addVisible"
          @close="closeChooseMaterial"
        />
        <!-- <newChooseMaterial :isClip="true" :visible="addVisible" modelType="audio" @close="closeChooseMaterial" /> -->
      </div>
    </a-spin>
    <!-- 新建模板进入页面后的提示 -->
    <addTemplateNext
      ref="addTemplateNextDialog"
      :zIndex="9999999999"
      @closeModelState:closeType="closeModelState"
      :template_public="queryData.templateType"
    ></addTemplateNext>
  </a-config-provider>

  <!-- 初始ai智能生图抽屉 -->
  <AiCreateImg
    ref="AiCreateImgRef"
    :aiModelList="aiModelList"
    @getTemplateData="getAiCreateTemplateData"
    @cancel="manualCreation"
  ></AiCreateImg>

  <!-- 组件修改的ai智能生图抽屉 -->
  <AiCreateImg_Drawer
    ref="AiCreateImg_DrawerRef"
    :ai_requestData="ai_requestData"
    :aiModelList="aiModelList"
    @changeChecked="changeChecked"
  >
  </AiCreateImg_Drawer>

  <!-- 混剪预览延迟进入弹窗 -->
  <awaitToMixedCutPreview
    ref="awaitToMixedCutPreviewRef"
    @timerOver="$router.push(toMixedCutPreviewUrl)"
  >
  </awaitToMixedCutPreview>
</template>

<script>
import {
  defineComponent,
  reactive,
  toRefs,
  ref,
  computed,
  nextTick,
  createVNode,
  onMounted,
  onUnmounted,
  h,
  watch,
} from "vue";
// 生成随机id
import { nanoid } from "nanoid";
// 基础模板信息
import {
  base_data,
  base_VideoMashup,
  baseTts_config,
  baseSubtitle,
  getSubmitData,
  // 回显比例的方法
  resetXY,
  // 手机组件的宽度高度
  phoneWidth,
  phoneHeight,
  // 计算文本宽度的方法
  getTextWidthUsingCanvas,
  getNowTime,
  getAllTemplateAudio,
  templateListLength,
  baseGlobal_tts_config,
  baseText_config,
  splitTextAndRemoveCommas,
  textSubtitleHeight,
  yOffset,
  calculateDraggableArea,
  titleHeightratio,
} from "../utools/index.js";
import {
  CheckCircleOutlined,
  LeftOutlined,
  ExclamationCircleOutlined,
  PicCenterOutlined,
  DeleteOutlined,
  StarOutlined,
  VerticalAlignBottomOutlined,
  PlusOutlined,
  HolderOutlined,
  CloseCircleFilled,
} from "@ant-design/icons-vue";
import { useRouter, useRoute, onBeforeRouteLeave } from "vue-router";
// 每一项视频组
import videoGroupCard from "./components/videoGroupCard.vue";
import videoConfiguration from "./components/videoConfiguration.vue";
import videoSimulation from "./components/videoSimulation.vue";
import AuthoringScript from "../../components/../CreationCenter/modules/AuthoringScript.vue";
import AIWritingAssistant from "./components/AIWritingAssistant.vue";
import NewGuidExperience from "./components/NewGuidExperience.vue";
import saveTemplate from "./components/saveTemplate.vue";

// ai智能生图抽屉
import AiCreateImg_Drawer from "./components/Component/AiCreateImg_Drawer.vue";
// import { sizeData } from "../utools/index.js";

// 头部组件
import navBack from "../components/navBack.vue";
// 可编辑头部
import EditableHead from "@/views/shotstack/MuseMixedCut/components/EditableHead.vue";
// 拖拽
import Draggable from "vuedraggable";
// 字幕与配音编辑抽屉
import SubtitledubbingDrawer from "./components/SubtitlesAndDubbingDrawer.vue";
// 全局字幕与配音抽屉
import GlobalSubtitledubbingDrawer from "./components/globalSubtitledubbingDrawer.vue";
// 文字标题抽屉
import LiteralTitleDrawer from "./components/LiteralTitleDrawer.vue";
// 全局文字标题抽屉
import GlobalTitleDrawers from "./components/GlobalTitleDrawers.vue";
// ai智能生图抽屉
import AiCreateImg from "./components/AiCreateImg.vue";
//  弹窗
import baseModel from "@/components/baseModel/baseModel.vue";

// AI配图
// import PlotDialog from "./components/PlotDialog.vue";

//

// 用于测量x位置的 标准字体大小

import {
  import_fontSize,
  import_title_fontSize,
} from "@/common/utils/richTextProcessing.js";

// 选择文件组件
import ChooseMaterial from "@/views/shotstack/EditingCenter/modules/bottomSet/components/chooseMaterial.vue";
// ant 相关
import { message, Modal } from "ant-design-vue";
// 封装的请求
import request from "@/common/utils/request";
// 模板添加完成后跳转到这个页面的提示弹窗
import addTemplateNext from "@/views/shotstack/CreationCenter/components/addTemplateNext.vue";

import newChooseMaterial from "@/views/shotstack/EditingCenter/modules/bottomSet/components/newChooseMaterial.vue";

// 进入混剪倒计时弹窗
import awaitToMixedCutPreview from "@/views/shotstack/components/dialogComponent/awaitToMixedCutPreview.vue";

// 仓库
import { useStore } from "vuex";
// 按标点符号拆分
// import { splitTextAndRemoveCommas } from "@/views/shotstack/MuseMixedCut/utools/index.js";
export default defineComponent({
  name: "mixedCutCreat",
  components: {
    newChooseMaterial,
    CheckCircleOutlined,
    CloseCircleFilled,
    LeftOutlined,
    PicCenterOutlined,
    ExclamationCircleOutlined,
    GlobalTitleDrawers,
    // PlotDialog,
    AiCreateImg_Drawer,
    videoGroupCard,
    ChooseMaterial,
    DeleteOutlined,
    StarOutlined,
    videoConfiguration,
    videoSimulation,
    AuthoringScript,
    AIWritingAssistant,
    LiteralTitleDrawer,
    awaitToMixedCutPreview,
    baseModel,
    HolderOutlined,
    SubtitledubbingDrawer,
    EditableHead,
    navBack,
    VerticalAlignBottomOutlined,
    PlusOutlined,
    Draggable,
    NewGuidExperience,
    saveTemplate,
    addTemplateNext, // 模板添加完成后跳转到这个页面的提示弹窗
    GlobalSubtitledubbingDrawer, //全局字幕与配音抽屉
    AiCreateImg, // ai智能生图抽屉
  },

  setup() {
    const router = useRouter();
    const route = useRoute();
    const state = reactive({
      isGobackModal: false,
      authoringScript: null,
      aiWritingAssistant: null,
      newGuidExperience: null,
      savetemplate: null,
      // 根据 route.query.viewType  判断按钮的显示与影藏
      isShowTopBtn: true,
      explableData: null,
      clipRole: [],
      // ai绘图模型列表, 只有混剪才获取
      aiModelList: [],
      tipText: "加载中...",
      // 混剪预览延迟进入弹窗实例
      awaitToMixedCutPreviewRef: null,

      // 去混剪携带的url参数
      toMixedCutPreviewUrl: "",
    });
    // 仓库
    const store = useStore();
    // 判断仓库视频数据没有空值
    const allVideoGroup = computed(() => {
      return store.getters.allVideoGroup;
    });

    // ai配图气泡
    // const PlotDialogRef = ref(null);

    // ai智能生图抽屉
    const AiCreateImgRef = ref(null);

    // 视频组中发送ai请求需要的模型id等信息
    const ai_requestData = computed(() => {
      if (state.aiModelList.length) {
        const find = state.aiModelList.find((ele) => ele.selected == 1);
        return {
          modelId: find.modelId,
          feature_id: find.feature_id || "",
        };
      } else {
        return {
          modelId: "",
          feature_id: "",
        };
      }
    });

    // 控制骨架屏显示
    const loading = ref(false);

    // 模板广场页面带过来的 id
    const queryData = computed(() => {
      return {
        viewType: route.query?.viewType, // 1模板详情, 2混剪详情
        isAi: route.query?.isAi, // true 为ai页面过来的
        id: route.query?.id, // 详情id
        key: route.query?.key, // 获取详情的id键名
        type: route.query?.type, // 用于区分新建的类型
        templateType: route.query?.templateType, // 用于区分查看模板详情的类型 1为我的模板 2为模板广场
        createType: route.query?.createType, // 用于区分模板创建类型 1为网络连接 2为素材库 3为手动创建
        useType: route.query?.useType, // 用于区分模板使用的类型 edit 编辑 view 详情 use使用
        typeofuse: route.query?.typeofuse, // 用于区分模板点击使用使用的类型 myTemplate为我的模板 squareTemplate为模板广场
        openType: route.query?.openType, // 用于区分模板点击使用使用的类型 myTemplate为我的模板 squareTemplate为模板广场
        unique_id: route.query?.unique_id, // 爆破款文案库使用时,请求详情携带的唯一id
        notOpenAi: route.query?.notOpenAi, // 从混剪页面回来, 不打开ai生图抽屉
      };
    });

    const isShowTitleBtn = computed(() => {
      let showData = {
        OfficialTemplate: {
          text: "保存为官方模板",
          show: false,
        }, // 官方模板
        MyTemplate: {
          text: "保存为模板",
          show: false,
        }, // 我的模板
        preview: {
          text: "视频混剪预览",
          show: false,
        }, // 视频混剪预览
        saveMontage: {
          text: "保存混剪项目",
          show: false,
        },
      };
      // 查看或创建的是模板
      if (queryData.value.viewType == 1) {
        // 查看或编辑
        if (
          queryData.value?.id !== undefined &&
          typeof +queryData.value?.id == "number"
        ) {
          // 创建模板选择素材生成了id
          if (
            queryData.value?.createType !== undefined &&
            typeof +queryData.value?.createType == "number"
          ) {
            showData.saveMontage.show = false;
            showData.OfficialTemplate.show = true;
            showData.OfficialTemplate.text = "保存为官方模板";
            showData.MyTemplate.show = true;
            showData.MyTemplate.text = "保存为模板";
          } else {
            // 我的模板查看编辑 或者使用模板创建混剪项目
            if (queryData.value.templateType == 1) {
              // 使用我的模板 创建 混剪项目
              if (queryData.value?.useType == "use") {
                showData.saveMontage.show = true;
                showData.preview.show = true;
                showData.MyTemplate.show = false;
                showData.OfficialTemplate.show = false;
                // 编辑模板
              } else if (queryData.value?.useType == "edit") {
                showData.saveMontage.show = false;
                showData.preview.show = false;
                showData.MyTemplate.show = true;
                showData.MyTemplate.text = "保存";
                showData.OfficialTemplate.show = true;
              } else if (queryData.value?.useType == "view") {
                // 我的模板 查看详情
                showData.saveMontage.show = false;
                showData.preview.show = false;
                showData.MyTemplate.show = true;
                showData.MyTemplate.text = "保存";
                showData.OfficialTemplate.show = true;
              }
            } else if (queryData.value.templateType == 2) {
              // 官方模板查看编辑,或者使用模板创混剪项目

              if (queryData.value?.useType == "use") {
                showData.saveMontage.show = true;
                showData.preview.show = true;
                showData.MyTemplate.show = false;
                showData.OfficialTemplate.show = false;
                // 编辑官方模板
              } else if (queryData.value?.useType == "edit") {
                showData.saveMontage.show = false;
                showData.preview.show = false;
                showData.MyTemplate.show = false;
                showData.MyTemplate.text = "保存";
                showData.OfficialTemplate.show = true;
              } else if (queryData.value?.useType == "view") {
                // 官方模板 查看详情
                showData.saveMontage.show = false;
                showData.preview.show = false;
                showData.MyTemplate.show = true;
                showData.MyTemplate.text = "保存";
                showData.OfficialTemplate.show = true;
              }

              // if (queryData.value?.useType == 1) {
              //   showData.saveMontage.show = true;
              //   showData.preview.show = true;
              //   showData.MyTemplate.show = false;
              //   showData.OfficialTemplate.show = false;
              // } else {
              //   // 编辑模板
              //   showData.saveMontage.show = false;
              //   showData.preview.show = false;
              //   showData.MyTemplate.show = true;
              //   showData.MyTemplate.text = "保存";
              //   showData.OfficialTemplate.show = true;

              // }
            }
          }
        } else {
          // 新创建的模板
          showData.saveMontage.show = false;
          showData.OfficialTemplate.show = true;
          showData.OfficialTemplate.text = "保存为官方模板";
          showData.MyTemplate.show = true;
          showData.MyTemplate.text = "保存为模板";
        }
      } else if (queryData.value.viewType == 2) {
        // 混剪预览的
        showData.OfficialTemplate = false;
        showData.MyTemplate = false;
        showData.preview.show = true;
        showData.preview.text = "视频混剪预览";
        showData.saveMontage.show = true;
        showData.saveMontage.text = "保存混剪项目";
      }
      return showData;
    });
    const groupCount = ref(0); //视频组数量
    const paramsData = computed(() => {
      return route.params;
    });

    // 新建进入模板广场后的弹窗提示
    const addTemplateNextDialog = ref(null);

    // 获取ai模型列表
    const getAiMod = async () => {
      const res = await request.get(
        "work_ai",
        `/user/ai/aiFeature/list?feature=text2image`
      );
      console.log(res, "ai绘画列表=======================");
      state.aiModelList = res.result;
    };

    onMounted(() => {
      // 移除混剪数据
      store.dispatch("RemoveVideoMashupData");
      // 获取花字数据

      // 模板详情, 打开弹窗
      if (!!queryData.value?.id) {
        if (queryData.value.viewType == 1 && !!queryData.value?.createType) {
          // debugger
          loading.value = false;
          // 刚创建的模板 查看详情, 打开弹窗提示用户
          addTemplateNextDialog.value &&
            addTemplateNextDialog.value.showModal();
          // setTimeout(() => {
          //   if (visibleState.value == true) {
          //     closeModelState();
          //   }
          // }, 3000);
        } else {
          loading.value = true;
        }
      }
      // 获得字体数据 + 花字 + 默认音色数据
      Promise.all([
        store.dispatch("getFlowerListData"),
        store.dispatch("getFontFamily"),
        store.dispatch("getRequestVoiceData"),
      ])
        .then(() => {
          setVuexData();
          if (route.query.viewType == "1") {
            state.isShowTopBtn = true;
          } else {
            // 获取ai模型列表
            getAiMod();
            state.isShowTopBtn = false;
          }
          // 获取ai模型列表

          // 页面刷新拦截提示
          window.addEventListener("beforeunload", setupBeforeUnloadListener);
        })
        .catch(() => {
          Modal.info({
            title: "提示",
            okText: "重试",
            keyboard: false,
            content: h("div", {}, [h("p", "参数获取失败!")]),
            onOk() {
              // 刷新页面
              window.location.reload();
            },
          });
        });
      // 有id 则获取数据 否则设置为默认数据
    });

    // 文件夹 id 请求文件
    const initMediaList = (id) => {
      let params = {
        merchant_folder_statck_id: id,
        multimedia_tag_id: "",
        pageSize: 10, // 限制取10条
        page: 1,
      };
      request
        .post("/work_ai", "/user/shotstack/media/list", params)
        .then((res) => {
          state.initMediaData = res.result.data;
          let data = base_VideoMashup();
          // 判断是混剪还是模板 赋值name
          if (queryData.value.viewType == 1) {
            // 混剪进来的
            data.name = `模板项目${getNowTime()}`;
          } else if (queryData.value.viewType == 2) {
            // 模板进来的
            data.name = `混剪项目${getNowTime()}`;
          }
          const baseData = base_data();
          let mixCutData = state.initMediaData.map((item, index) => {
            return {
              ...baseData,
              name: "视频组" + (index + 1),
              material_list: [
                ...baseData.material_list,
                {
                  end_time: 3000,
                  id: item.id,
                  material_duration: item.material_duration,
                  material_extension: item.material_extension,
                  material_name: item.material_name,
                  material_size: item.material_size,
                  material_url: item.material_url,
                  scene_type: item.material_type,
                },
              ],
            };
          });

          // 过滤一下 空的 subtitle
          mixCutData.forEach((ele) => {
            ele.tts_config.forEach((item) => {
              if (item.subtitle.length > 1) {
                item.subtitle = item.subtitle.filter((item) => {
                  return !!item.text.trim() && item.text.trim() != "\n";
                });
                item.ssmlContent = item.subtitle
                  .map(
                    (i) =>
                      `<speak subid="${i.subtitle_id}" tts_id="${item.tts_id}">${i.text}</speak>`
                  )
                  .join("");
              }
            });
          });

          data.resource_data = mixCutData;
          console.log(mixCutData, "9191919919");
          store.commit("SET_VIDEOMASHUP", data);
          groupCount.value = VideoMashup.value?.resource_data?.length;
        });
    };

    const setupBeforeUnloadListener = (e) => {
      e.preventDefault();
      e.returnValue = "刷新页面可能会导致编辑的数据丢失，是否继续刷新？";
      return "刷新页面可能会导致编辑的数据丢失，是否继续刷新？";
    };

    const visibleState = computed(() => {
      return addTemplateNextDialog.value.visibleState;
    });

    // 获取默认数据或详情数据
    const setVuexData = async () => {
      !!queryData.value?.id
        ? (() => {
            getTemplateData();
            // 模板详情, 打开弹窗
            if (
              queryData.value.viewType == 1 &&
              !!queryData.value?.createType
            ) {
              // debugger
              loading.value = false;
              // 刚创建的模板 查看详情, 打开弹窗提示用户
              addTemplateNextDialog.value &&
                addTemplateNextDialog.value.showModal();
            } else {
              loading.value = true;
            }
          })()
        : manualCreation(); // 手动新建模板
    };

    const globalLabel = ref("");
    // 判断全局文字标题状态
    const GlobTitleState = (message) => {
      globalLabel.value = message;
    };

    // 仓库中的混剪数据
    const VideoMashup = computed(() => {
      return store.state.shotstack.VideoMashup;
    });

    // ai配图的开关 1开 2关
    const ai_mapping = computed({
      get() {
        return VideoMashup.value?.ai_mapping || 1;
      },
      set(val) {
        VideoMashup.value.ai_mapping = val;
        store.dispatch("SetVideoMashup", VideoMashup.value);
      },
    });

    // 获取顶部标题
    const titleText = computed({
      get() {
        // 如果仓库中有名字
        return VideoMashup.value.name;
      },
      set(val) {
        VideoMashup.value.name = val;
      },
    });
    // 获取详情, viewType:1 模板详情, viewType:2 混剪详情
    let timerId = ref(null);

    const getTemplateData = async () => {
      const queryParams = {
        //  id: queryData.value.id,
        [queryData.value.key]: queryData.value.id,
      };
      // 0 为复制   后端默认为1
      if (route.query.openType === "copy") {
        queryParams.is_edit = 0;
      }
      let res;

      console.log(
        typeof queryData.value?.isAi,
        "queryData.value?.isAi 是不是ai"
      );
      let url =
        queryData.value.viewType == 1
          ? "/user/shotstack/template/detail"
          : queryData.value?.isAi == "true"
          ? "/user/shotstack/inspirationText/record/detail"
          : "/user/shotstack/editing/record/detail";
      // 如果是ai 则需要添加一个唯一id 作为请求参数
      if (queryData.value?.isAi == "true") {
        queryParams.unique_id = queryData.value.unique_id;
      }
      if (queryData.value.useType) {
        queryParams.useType = queryData.value.useType;
      }
      try {
        res = await request.get("/work_ai", url, queryParams);

        // if (queryData.value?.isAi == "true") {

        // }
        console.log(res, "模板详情");
        if (Array.isArray(res.result) && !res.result.length) {
          timerId.value = setTimeout(() => {
            getTemplateData();
          }, 5000);
          return;
        }
        // 如果是ai生成的, 调用智能生图中的获取详情方法
        // && queryData.value?.notOpenAi != 'true'
        if (queryData.value?.isAi == "true") {
          AiCreateImgRef.value &&
            AiCreateImgRef.value.getDetaile({
              inspiration_text_id: queryData.value.id,
              unique_id: queryData.value.unique_id,
            });
          loading.value = false;
          addTemplateNextDialog.value &&
            addTemplateNextDialog.value.closeModal();
          // 如果没有数据打开弹窗
          if (res.result.resource_data.length == 0) {
            AiCreateImgRef.value && AiCreateImgRef.value.open();
            // localStorage.setItem("nodeOpenAi", 'false')
            return;
          }
        }
        loading.value = false;
        addTemplateNextDialog.value && addTemplateNextDialog.value.closeModal();
        state.explableData = JSON.parse(
          JSON.stringify(res.result.resource_data)
        );
      } catch (error) {
        clearTimeout(timerId.value);
        loading.value = false;
        addTemplateNextDialog.value && addTemplateNextDialog.value.closeModal();
        // 有token 才提示, 否则会出现弹窗冲突, 否则弹回首页
        if (store.state?.user.token) {
          Modal.info({
            title: "提示",
            okText: "返回",
            keyboard: false,
            content: h("div", {}, [h("p", "模板创建失败!")]),
            onOk() {
              // router.push(
              //   `/workShotstack/materialCenter/TemplateList?templateType=${
              //     queryData.value?.templateType || "0"
              //   }`
              // );
              router.back();
            },
          });
        } else {
          router.push("/workShotstack/home");
        }
        return;
      }

      processingData(res);
    };

    // 获取随机的花字样式
    const getFlower = () => {
      return [
        FlowerArr.value[Math.floor(Math.random() * 5)],
        FlowerArr.value[Math.floor(Math.random() * FlowerArr.value.length)],
      ];
    };

    // 手动创建模板拆分函数
    const manualCreation = async () => {
      const res = await request.get(
        "/work_ai",
        `/user/platform/uniqueId/by/num`,
        {
          num: 32,
        }
      );

      let data = base_VideoMashup();
      // 设置默认的ai配图为开启
      queryData.value.viewType == 2 && (data.ai_mapping = 1);
      // 设置唯一值
      data.unique_id = res.uniqueId;
      // 纯新增的项 需要手动设置type
      data.type = +queryData.value.type;

      // 判断是混剪还是模板 赋值name
      if (queryData.value.viewType == 1) {
        // 混剪进来的
      } else if (queryData.value.viewType == 2) {
        // 文案库页面跳转进来的  || AI创作页面跳转进来的
        if (route.query.Textlibrary || route.query.sceneCreation ||  route.query.TextImitation) {
          // 判断字幕是否超出限制
          let isOverTextlength = store.state.shotstack.sceneCreationTexts.some(
            (ele) => ele.length > 500
          );
          // 判断副标题是否超出限制
          let isOverSubtitlTitlelength =
            store.state.shotstack.sceneCreationSubtileTitles.some(
              (ele) => ele.length > 500
            );
          // 判断标题是否超出限制
          let isOverTitlelength =
            store.state.shotstack.sceneCreationTitles.some(
              (ele) => ele.length > 500
            );
          // 如果超出限制给出提示
          if (
            isOverTextlength ||
            isOverTitlelength ||
            isOverSubtitlTitlelength
          ) {
            message.warning("字幕或标题超出500字限制，系统将自动截取");
          }

          // 处理全局标题------start----------
          data.global_text_config.configs =
            store.state.shotstack.sceneCreationTitles.map((ele, index) => {
              const { scaleTextWidth, scaleTextHeight } = resetXY(
                data.showHeight,
                data.showWidth
              );

              // 副标题的此项数据
              const subtitle_item =
                store.state.shotstack.sceneCreationSubtileTitles[index];

              // 副标题字体大小
              const subtitle_fontsieze = import_fontSize;

              const basetext_config = baseText_config();
              // const basetext_font_size =
              //   basetext_config.font_size / scaleTextWidth;
              // 主标题字体大小
              const basetext_font_width = getTextWidthUsingCanvas(
                ele,
                import_title_fontSize,
                basetext_config.font_family
              );
              const basetext_x = (phoneWidth - basetext_font_width) / 2;

              // 如果有子标题
              if (!!subtitle_item) {
                // 获得字体大小转换的比例
                const sizeData = calculateDraggableArea(
                  data.width,
                  data.height
                );

                // 副标题字体大小
                let sub_basetext_font_width = getTextWidthUsingCanvas(
                  subtitle_item,
                  subtitle_fontsieze,
                  basetext_config.font_family
                );
                const sub_GlobalTitleX =
                  (phoneWidth - sub_basetext_font_width) / 2;
                // 全局标题换行的数量, 根据换行数量来判断副标题位置
                let lineFeedNum = ele.match(/\n/g)?.length || 0;

                // 随机的两组标题花字样式
                const preset_styles_config_Arr = getFlower();

                const mindY = sizeData.draggableHeight / titleHeightratio;
                const subY =
                  sizeData.draggableHeight / textSubtitleHeight +
                  lineFeedNum * yOffset;
                return [
                  {
                    ...baseText_config(),
                    text: ele,
                    x: basetext_x,
                    preset_styles_config: {
                      ...preset_styles_config_Arr[0],
                      type: 1,
                    },
                    y: mindY,
                  },
                  {
                    ...baseText_config(),
                    text: subtitle_item,
                    x: sub_GlobalTitleX,
                    y: subY,
                    preset_styles_config: {
                      ...preset_styles_config_Arr[1],
                      type: 1,
                    },
                    font_size: 14,
                  },
                ];
              } else {
                return [
                  {
                    ...baseText_config(),
                    text: ele,
                    x: basetext_x,
                  },
                ];
              }
            });
          data.global_text_config.type = 1;
          // 处理全局标题------end----------

          // 处理全局字幕配音 ----- start------------
          const { scaleWidth, scaleHeight } = resetXY(
            data.showHeight,
            data.showWidth
          );
          data.global_tts_config.configs = [
            {
              ...baseGlobal_tts_config(),
              tab_id: "audio",
            },
            ...store.state.shotstack.sceneCreationTexts.map((item) => {
              let subtitleList = splitTextAndRemoveCommas(item.slice(0, 500));
              const ttsConfig = baseTts_config();
              subtitleList = subtitleList?.map((ele) => {
                const font_size = ttsConfig.subtitle[0].font_size / scaleWidth;
                const font_width = getTextWidthUsingCanvas(
                  ele,
                  font_size,
                  ttsConfig.subtitle[0].font_family
                );
                const x = (phoneWidth - font_width) / 2;
                return {
                  ...ttsConfig.subtitle[0],
                  text: ele,
                  ssml: `<speak>${ele}</speak>`,
                  subtitle_id: nanoid(),
                  x,
                };
              });
              return {
                ...baseGlobal_tts_config(),
                subtitle: subtitleList,
                tab_id: "text",
              };
            }),
          ];
          data.global_tts_config.type = 1; //1-使用全局字幕配音，0-不使用全局字幕配音

          nextTick(() => {
            // 打开全局弹窗
            openGlobalSubtitledubbingDrawer();
            // 导入结束之后, 将所有的缓存数据重置
            store.commit("SET_SCENE_CREATION_TEXTS", []);
            store.commit("SET_SCENE_CREATION_TITLES", []);
            store.commit("SET_SCENE_CREATION_SUBTITLES", []);
          });
          // 处理全局字幕配音 ----- end------------
        }
        // 脚本进来的
        if (route.query.mixcutId) {
          let httpsUrl = "";
          // 脚本广场跳转
          if (route.query.scriptType) {
            httpsUrl = "/user/shotstack/script-line/org/detail";
          } else {
            // 我的脚本跳转
            httpsUrl = "/user/shotstack/script-line/detail";
          }
          request
            .get("/work_ai", httpsUrl, {
              scriptLineId: route.query.mixcutId,
            })
            .then(async (res) => {
              console.log(res, "脚本数据123123");
              const baseData = base_data();
              // 判断是混剪还是模板 赋值name
              if (queryData.value.viewType == 1) {
                // 混剪进来的
                baseData.name = `模板项目${getNowTime()}`;
              } else if (queryData.value.viewType == 2) {
                // 模板进来的
                baseData.name = `混剪项目${getNowTime()}`;
              }
              const ttsConfig = baseTts_config();
              // 判断文案是否超出限制
              res.detail.script_scenes?.some(
                (item) =>
                  item.line_audio[0].elements[0][0].text?.trim()?.length >
                    500 && message.warning("文案超过500字，系统将随机截取")
              );
              let mixCutData = res.detail.script_scenes.map((item, index) => {
                // 是数组 且每一项都有总时长
                if (
                  Array.isArray(item?.audio_detail) &&
                  item?.audio_detail
                    ?.filter((ele) => ele.tab_id == "text")
                    ?.every((i) => typeof i?.duration == "number")
                ) {
                  return {
                    ...baseData,
                    name: item.name,
                    tts_config: item?.audio_detail,
                    material_list: item.example_url?.map((item) => {
                      return {
                        ...item,
                        start_time: 0,
                      };
                    }),
                  };
                } else {
                  let subtitleList = item.line_audio[0].elements[0][0].text
                    ?.trim()
                    ?.slice(0, 500)
                    ?.split("\n");
                  subtitleList = subtitleList?.map((ele) => {
                    return {
                      ...ttsConfig.subtitle[0],
                      elements: item.line_audio[0].elements[0],
                      text: ele,
                      ssml: `<speak>${ele}</speak>`,
                      subtitle_id: nanoid(),
                      x: (phoneWidth - getTextWidthUsingCanvas(ele, 16)) / 2,
                    };
                  });
                  const tts_id = nanoid();
                  return {
                    ...baseData,
                    name: item.name,
                    tts_config: [
                      {
                        ...ttsConfig,
                        name: item.audio_config.name,
                        img: item.audio_config.img,
                        emotion_category: item.audio_config.emotion_category,
                        emotion_intensity: item.audio_config.emotion_intensity,
                        start_time: item.audio_config.start_time,
                        tone_id: item.audio_config.voice_type,
                        volume: item.audio_config.volume,
                        speed: item.audio_config.speed,
                        tts_id,
                        subtitle: subtitleList,
                        ssmlContent: subtitleList
                          .map(
                            (i) =>
                              `<speak subid="${i.subtitle_id}" tts_id="${tts_id}">${i.text}</speak>`
                          )
                          .join(""),
                      },
                      {
                        ...ttsConfig,
                        tab_id: "audio",
                      },
                    ],
                    material_list: item.example_url.map((item) => {
                      return {
                        ...item,
                        start_time: 0,
                      };
                    }),
                  };
                }
              });

              // 过滤一下 空的 subtitle
              mixCutData.forEach((ele) => {
                ele.tts_config.forEach((item) => {
                  if (item.subtitle.length > 1) {
                    item.subtitle = item.subtitle.filter((item) => {
                      return !!item.text.trim() && item.text.trim() != "\n";
                    });
                    item.ssmlContent = item.subtitle
                      .map(
                        (i) =>
                          `<speak subid="${i.subtitle_id}" tts_id="${item.tts_id}">${i.text}</speak>`
                      )
                      .join("");
                  }
                });
              });

              data.resource_data = mixCutData;
              console.log(mixCutData, "9191919919");
              state.tipText = "";
              loading.value = true;
              // 获取所有视频组的音频数据
              const newData = await getAllTemplateAudio(data.resource_data);
              // TODO 反向修改脚本数据 - 待完成
              data.resource_data.forEach((ele, index) => {
                res.detail.script_scenes[index].audio_detail = ele.tts_config;
              });
              await StoreScriptData(res.detail).finally(() => {
                console.log(data, " 获取音频之后的数据-------------");
                store.dispatch("SetVideoMashup", data);
                groupCount.value = VideoMashup.value?.resource_data?.length;
                nextTick(() => {
                  loading.value = false;
                });
              });
            });
        } else if (route.query.materid) {
          initMediaList(route.query.materid);
          return;
        }
      }

      // 判断是混剪还是模板 赋值name
      if (queryData.value.viewType == 1) {
        // 混剪进来的
        data.name = `模板项目${getNowTime()}`;
      } else if (queryData.value.viewType == 2) {
        // 模板进来的
        data.name = `混剪项目${getNowTime()}`;
      }

      // 新增处理数据的x和y
      // console.log(JSON.parse(JSON.stringify(data)), "datadata");
      store.dispatch("SetVideoMashup", data);
      groupCount.value = VideoMashup.value?.resource_data?.length;
    };

    // 获取音频之后 反向修改 脚本页面的数据
    const StoreScriptData = async (data) => {
      // 0 - 脚本广场 org/shotstack/script-line/update, >0 - 我的脚本
      // let url = data.user_id == 0 ? '/org/shotstack/script-line/update' : '/user/shotstack/script-line/update'
      const { script_scenes } = data;
      const res = await request.put(
        "/work_ai",
        "/user/shotstack/script-line/update",
        {
          ...data,
        }
      );
      console.log(res, "反向修改是否成功");
    };

    // 花字列表
    const FlowerArr = computed(() => {
      return store.state.shotstack.FlowerArr;
    });
    const setPreset_styles_config = (data, type) => {
      // 添加花字 需要的数据
      const findFlowerFont_title = FlowerArr.value.find(
        (item) => item.name == "黄心黑边"
      );
      const findFlowerFont_text = FlowerArr.value.find(
        (item) => item.name == "白心黑边"
      );
      if (type == "title") {
        !data.preset_styles_config &&
          (data.preset_styles_config = {
            box: 0,
            type: 1,
            fontcolor: findFlowerFont_title.fontcolor || "",
            bordercolor: findFlowerFont_title.bordercolor || "",
            id: findFlowerFont_title.id || "",
            borderw: findFlowerFont_title.borderw || "",
            boxcolor: findFlowerFont_title.boxcolor || "",
            box_color_alpha: findFlowerFont_title.box_color_alpha || "",
            boxborderw: findFlowerFont_title.boxborderw || "",
            // boxradius: findFlowerFont_title.boxradius || "",
          });
        return;
      }
      !data.preset_styles_config &&
        (data.preset_styles_config = {
          box: 0,
          type: 1,
          fontcolor: findFlowerFont_text.fontcolor || "",
          bordercolor: findFlowerFont_text.bordercolor || "",
          id: findFlowerFont_text.id || "",
          borderw: findFlowerFont_text.borderw || "",
          boxcolor: findFlowerFont_text.boxcolor || "",
          box_color_alpha: findFlowerFont_text.box_color_alpha || "",
          boxborderw: findFlowerFont_text.boxborderw || "",
          // boxradius: findFlowerFont_title.boxradius || "",
        });
    };

    // 处理res数据
    const processingData = (res) => {
      // 宽高
      if (res.result.width) {
        if (res.result.width < 360) res.result.width = 360;
        if (res.result.width > 1920) res.result.width = 1920;
        // 判断用户是想增加还是减少
        if (res.result.width % 4 !== 0) {
          if (res.result.width + 4 > 1920) {
            // 用户意图增加，向上取最近的4的整数倍
            res.result.width -= 4 - (res.result.width % 4);
          } else if (res.result.width - 4 < 360) {
            // 用户意图减少，向下取最近的4的整数倍
            res.result.width += res.result.width % 4;
          } else {
            res.result.width += res.result.width % 4;
          }
        }
      } else {
        res.result.width = 1920;
      }
      if (res.result.height) {
        if (res.result.height < 360) res.result.height = 360;
        if (res.result.height > 1920) res.result.height = 1920;
        // 判断用户是想增加还是减少
        if (res.result.height % 4 !== 0) {
          if (res.result.height + 4 > 1920) {
            // 用户意图增加，向上取最近的4的整数倍
            res.result.height -= 4 - (res.result.height % 4);
          } else if (res.result.height - 4 < 360) {
            // 用户意图减少，向下取最近的4的整数倍
            res.result.height += res.result.height % 4;
          } else {
            res.result.height += res.result.height % 4;
          }
        }
      } else {
        res.result.height = 1080;
      }

      // 获得大比例, 用于回显 fontsize 和后端相同的效果
      const oldScaleData = resetXY(res.result.height, res.result.width);

      // 换算比例, 用于回显和后端预览相同的效果 -- 得到小比例
      res.result.showHeight = res.result.height / 4;
      res.result.showWidth = res.result.width / 4;

      // x和y 除比例 即为还原的比例
      const { scaleWidth, scaleHeight } = resetXY(
        res.result.showHeight,
        res.result.showWidth
      );

      console.log(scaleWidth, scaleHeight, "比例比例");
      const sizeData = calculateDraggableArea(
        res.result.showWidth,
        res.result.showHeight
      );

      res.result.resource_data.forEach((ele) => {
        ele.tts_config.forEach((i) => {
          i.subtitle.forEach((item) => {
            // 判断是否是编辑或者其他方式回显的数据
            // 字体大小乘以大比例 再乘以小比例, 回显提交前的数据
            if (item.y !== "0" || item.x !== "0") {
              item.font_size =
                (+item.font_size / oldScaleData.scaleWidth) * scaleWidth;
            }
            if (item.x === "0") {
              // const font_size = item.font_size / scaleWidth;
              const font_width = getTextWidthUsingCanvas(
                item.text,
                import_fontSize,
                item.fontFamily
              );
              const x = (phoneWidth - font_width) / 2;
              // 初始的x位置
              item.x = x;
              item.showX = sizeData.draggableWidth / 2;
            } else {
              item.x = item.x / 4 / scaleWidth;
            }
            if (item.y === "0") {
              item.y = sizeData.draggableHeight / 1.35;
            } else {
              item.y = item.y / 4 / scaleWidth;
            }

            // 判断有没有花字数据, 添加花字数据
            setPreset_styles_config(item, "sub");
          });
        });

        ele.text_config.forEach((item) => {
          // 字体大小乘以大比例 再乘以小比例, 回显提交前的数据
          if (item.y !== "0" || item.x !== "0") {
            item.font_size =
              (+item.font_size / oldScaleData.scaleWidth) * scaleWidth;
          }
          if (item.x === "0") {
            // const font_size = item.font_size / scaleWidth;
            const font_width = getTextWidthUsingCanvas(
              item.text,
              import_fontSize,
              item.fontFamily
            );
            const x = (phoneWidth - font_width) / 2;
            // 初始的x位置
            item.x = x;
            item.showX = sizeData.draggableWidth / 2;
          } else {
            item.x = item.x = item.x / 4 / scaleWidth;
          }
          if (item.y === "0") {
            item.y = sizeData.draggableHeight / 20;
          } else {
            item.y = item.y / 4 / scaleWidth;
          }

          // 判断有没有花字数据, 添加花字数据
          setPreset_styles_config(item, "title");
        });
      });

      res.result.global_text_config.configs.forEach((ele) => {
        ele.forEach((item) => {
          if (item.y !== "0" || item.x !== "0") {
            item.font_size =
              (+item.font_size / oldScaleData.scaleWidth) * scaleWidth;
          }
          if (item.x === "0") {
            const font_size = item.font_size / scaleWidth;
            const font_width = getTextWidthUsingCanvas(
              item.text,
              import_title_fontSize,
              item.fontFamily
            );
            const x = (phoneWidth - font_width) / 2;
            // 初始的x位置
            item.x = x;
            item.showX = sizeData.draggableWidth / 2;
          } else {
            item.x = item.x = item.x / 4 / scaleWidth;
          }
          if (item.y === "0") {
            item.y = sizeData.draggableHeight / 20;
          } else {
            item.y = item.y / 4 / scaleWidth;
          }

          // 判断有没有花字数据, 添加花字数据
          setPreset_styles_config(item, "title");
        });
      });

      res.result.global_tts_config.configs.forEach((ele) => {
        ele.subtitle.forEach((item) => {
          if (item.y !== "0" || item.x !== "0") {
            item.font_size =
              (+item.font_size / oldScaleData.scaleWidth) * scaleWidth;
          }
          if (item.x === "0") {
            const font_size = item.font_size / scaleWidth;
            const font_width = getTextWidthUsingCanvas(
              item.text,
              import_fontSize,
              item.fontFamily
            );
            const x = (phoneWidth - font_width) / 2;
            // 初始的x位置
            item.x = x;
            item.showX = sizeData.draggableWidth / 2;
          } else {
            item.x = item.x = item.x / 4 / scaleWidth;
          }
          if (item.y === "0") {
            item.y = sizeData.draggableHeight / 1.35;
          } else {
            item.y = item.y / 4 / scaleWidth;
          }

          // 判断有没有花字数据, 添加花字数据
          setPreset_styles_config(item, "sub");
        });
      });

      // 默认混剪 的ai配图打开
      queryData.value.viewType == 2 && (res.result.ai_mapping = 1);

      // 初始设置type
      store.dispatch("SetVideoMashup", res.result);
      groupCount.value = VideoMashup.value?.resource_data?.length;

      loading.value = false;
    };

    const getGroupName = async () => {
      let name = `视频组_${++groupCount.value}`;
      while (
        VideoMashup.value.resource_data.some((item) => item.name == name)
      ) {
        groupCount.value++;
        name = `视频组_${groupCount.value}`;
        await new Promise((resolve) => setTimeout(resolve, 1)); // 添加延迟等待，避免过快的循环调用
      }
      return name;
    };
    // 新增镜头组
    const addVideoGroupHandle = async () => {
      const videoGroups = store.state.shotstack.VideoMashup.resource_data;
      if (videoGroups.length < templateListLength) {
        const id = nanoid();
        groupCount.value = VideoMashup.value?.resource_data?.length;
        const name = await getGroupName();
        const data = base_data();
        videoGroups.push({
          ...data,
          id,
          name,
        });
        nextTick(() => {
          scrollToBottom();
        });
      } else {
        return message.error("最多只能添加10个镜头组");
      }
    };
    // 滚动条滚动到最底部
    const scrollToBottom = () => {
      const el = document.querySelector(".videoGroupCard_box");
      el.scrollTo({
        top: el.scrollHeight,
        behavior: "smooth",
      });
    };
    const showGobackModal = () => {
      state.isGobackModal = true;
    };
    const closeGobackModal = () => {
      state.isGobackModal = false;
    };
    // 离开前的询问
    const backClick = () => {
      Modal.confirm({
        title: "提示",
        icon: createVNode(ExclamationCircleOutlined),
        content: "当前页配置还未进行保存，直接离开数据不会保存和更新",
        cancelText: "确认返回",
        okText: "留在当前页",
        onOk: async () => {
          // 留在页面中
        },
        onCancel() {
          // debugger
          if (queryData.value.viewType == 1) {
            // 去模板列表
            router.push("/workShotstack/materialCenter/TemplateList");
          } else if (queryData.value.viewType == 2) {
            if (route.query?.sceneCreation) {
              router.push({
                name: "SceneCreation",
              });
              return;
            }
            
            if (route.query?.TextImitation) {
              router.push({
                name: "TextImitation",
              });
              return;
            }

            if (route.query?.Textlibrary) {
              router.push({
                name: "Textlibrary",
              });
              return;
            }
            // 去混剪列表
            router.push("/workShotstack/creationCenter/MixedCutIntroduction");
          } else {
            router.push("/workShotstack/home");
          }
        },
      });
    };
    const authoringScriptHandle = (type) => {
      state.authoringScript.showDrawer(type);
    };
    // AI写作助手
    const AIWritingAssistantHandle = () => {
      state.aiWritingAssistant.showDrawer();
    };

    // 视频混剪预览  + 保存
    const previewHandleLoding = ref(false);
    const previewHandle = () => {
      let isHasExplateUrl = VideoMashup.value.resource_data.some((item) =>
        item.material_list.some(
          (ele) => ele.system_default && ele.system_default == 1
        )
      );
      if (isHasExplateUrl) {
        return message.warning("请替换示例素材");
      } else {
        if (!allVideoGroup.value)
          return message.warning("视频组中的素材不能为空");

        if (!VideoMashup.value.name) return message.warning("请输入模板名称");

        if (queryData.value.useType == "use") {
          VideoMashup.value.id = 0;
          VideoMashup.value.type = 0;
          VideoMashup.value.unique_id = nanoid();
          store.dispatch("SetVideoMashup", VideoMashup.value);
        }
        // 视频混剪 - 复制按钮
        if (route.query.openType == "copy") {
          VideoMashup.value.id = "";
          VideoMashup.value.unique_id = nanoid();
          store.dispatch("SetVideoMashup", VideoMashup.value);
        }
        previewHandleLoding.value = true;
        loading.value = true;
        // 克隆后, 修改x和y轴数据, 最后提交的参数
        const submitData = getSubmitData();

        // 先调用视频预览接口 生成视频 拿到id

        try {
          request
            .post("/work_ai", "/user/shotstack/clip/preview", submitData)
            .then((res) => {
              if (res?.code && res.code != 1000) {
                throw new Error("视频生成失败!");
              }

              const queryParams = {
                id: res.result.id,
                name: submitData.name, // 添加submitData.name到查询参数中
              };
              // 如果是试用, 增加提示
              if (res?.result?.prompt) {
                message.warning({
                  content: () => res?.result?.prompt,
                  style: {
                    marginTop: "30px",
                  },
                  duration: 8,
                });
              }
              // 将route.query中的其他参数也合并到queryParams中
              for (const key in route.query) {
                if (route.query.hasOwnProperty(key)) {
                  queryParams[key] = route.query[key];
                }
              }
              // 过滤并构建queryPart，现在包括name参数
              const queryPart = Object.entries(queryParams)
                .filter(([key, value]) => key !== "id" && value !== undefined) // 注意：你之前的过滤条件似乎有误，这里修正了逻辑
                .map(([key, value]) => `${key}=${encodeURIComponent(value)}`) // 使用encodeURIComponent处理特殊字符
                .join("&");
              previewHandleLoding.value = false;
              loading.value = false;
              // 构建完整的跳转URL，确保即使没有其他参数也能正确构造URL
              const url = `/MixedCutPreview?qid=${res.result.id}&id=${
                queryParams.id
              }${queryPart ? `&${queryPart}` : ""}`;
              state.awaitToMixedCutPreviewRef.showModal();
              state.toMixedCutPreviewUrl = url;
            })
            .catch(() => {
              previewHandleLoding.value = false;
              loading.value = false;
              message.error("视频生成失败!");
            });
        } catch (error) {
          previewHandleLoding.value = false;
          loading.value = false;
          message.error("视频生成失败!");
        }
      }
    };

    // 打开全局文字标题抽屉
    const GloballedubbingDrawer = ref(null);
    const openGlobalT = () => {
      GloballedubbingDrawer.value && GloballedubbingDrawer.value.openDrawer();
    };

    // 打开字幕配音抽屉
    const subtitledubbingDrawer = ref(null);
    const openSubtitledubbingDrawer = (targetIndex) => {
      subtitledubbingDrawer.value &&
        subtitledubbingDrawer.value.openDrawer({
          index: targetIndex,
        });
    };
    // 打开文字标题抽屉
    const literalTitleDrawerComponent = ref(null);
    const openSettitleDrawer = (targetIndex) => {
      literalTitleDrawerComponent.value &&
        literalTitleDrawerComponent.value.openDrawer({
          index: targetIndex,
        });
    };
    // 打开全局字幕与配音抽屉
    const globalSubtitledubbingDrawer = ref(null);
    const openGlobalSubtitledubbingDrawer = () => {
      globalSubtitledubbingDrawer.value &&
        globalSubtitledubbingDrawer.value.openDrawer();
    };

    const AiCreateImg_DrawerRef = ref(null);
    // 打开智能生图
    const openAicreateImg = (index) => {
      AiCreateImg_DrawerRef.value &&
        AiCreateImg_DrawerRef.value.open({
          index: index,
        });
    };

    // 打开文件上传抽屉
    const addVisible = ref(false);
    const closeChooseMaterial = (data) => {
      console.log(data, "选择的文件");
      if (!!data) {
        subtitledubbingDrawer.value &&
          subtitledubbingDrawer.value.getVoiceData(data, getVoiceType.value);
      }

      addVisible.value = false;
    };
    const guideHandle = () => {
      state.newGuidExperience.showModal();
    };
    // 保存按钮
    const saveTemplateHandle = (type) => {
      let isHasExplateUrl = VideoMashup.value.resource_data.some((item) =>
        item.material_list.some(
          (ele) => ele.system_default && ele.system_default == 1
        )
      );
      if (isHasExplateUrl) {
        return message.warning("请替换示例素材");
      } else {
        state.savetemplate.showModal(type);
      }
    };

    const title_name = ref("");
    const updateName = (ev, element) => {
      element.name = ev;
      title_name.value = element.name;
      console.log(title_name.value, "修改后的值");
    };
    // 导入脚本
    const importScript = async (info) => {
      let data = base_VideoMashup();
      const baseData = base_data();
      const ttsConfig = baseTts_config();
      data.name = info.title;
      // 判断文案是否超出限制
      info.script_scenes?.some(
        (item) =>
          item.line_audio[0].elements[0][0].text?.trim()?.length > 500 &&
          message.warning("文案超过500字，系统将随机截取")
      );
      let mixCutData = info.script_scenes.map((item, index) => {
        if (
          Array.isArray(item?.audio_detail) &&
          item?.audio_detail
            ?.filter((ele) => ele.tab_id == "text")
            ?.every((i) => typeof i?.duration == "number")
        ) {
          return {
            ...baseData,
            name: item.name,
            tts_config: item?.audio_detail,
            material_list: item.example_url?.map((item) => {
              return {
                ...item,
                start_time: 0,
              };
            }),
          };
        } else {
          let subtitleList = item.line_audio[0].elements[0][0].text
            ?.trim()
            ?.slice(0, 500)
            ?.split("\n");
          subtitleList = subtitleList?.map((ele) => {
            return {
              ...ttsConfig.subtitle[0],
              elements: item.line_audio[0].elements[0],
              text: ele,
              ssml: `<speak>${ele}</speak>`,

              subtitle_id: nanoid(),
            };
          });
          const tts_id = nanoid();
          return {
            ...baseData,
            name: item.name,
            tts_config: [
              {
                ...ttsConfig,
                name: item.audio_config.name,
                img: item.audio_config.img,
                emotion_category: item.audio_config.emotion_category,
                emotion_intensity: item.audio_config.emotion_intensity,
                start_time: item.audio_config.start_time,
                tone_id: item.audio_config.voice_type,
                volume: item.audio_config.volume,
                speed: item.audio_config.speed,
                tts_id,
                subtitle: subtitleList,
                ssmlContent: subtitleList
                  .map(
                    (i) =>
                      `<speak subid="${i.subtitle_id}" tts_id="${tts_id}">${i.text}</speak>`
                  )
                  .join(""),
              },
              {
                ...ttsConfig,
                tab_id: "audio",
              },
            ],
            material_list: item.example_url?.map((item) => {
              return {
                ...item,
                start_time: 0,
              };
            }),
          };
        }
      });

      // 过滤一下 空的 subtitle
      mixCutData.forEach((ele) => {
        ele.tts_config.forEach((item) => {
          if (item.subtitle.length > 1) {
            item.subtitle = item.subtitle.filter((item) => {
              return !!item.text.trim() && item.text.trim() != "\n";
            });
            item.ssmlContent = item.subtitle
              .map(
                (i) =>
                  `<speak subid="${i.subtitle_id}" tts_id="${item.tts_id}">${i.text}</speak>`
              )
              .join("");
          }
        });
      });

      data.resource_data = mixCutData;
      state.tipText = "";
      loading.value = true;
      const newData = await getAllTemplateAudio(data.resource_data);
      store.dispatch("SetVideoMashup", data);
      data.resource_data.forEach((ele, index) => {
        info.script_scenes[index].audio_detail = ele.tts_config;
      });
      groupCount.value = VideoMashup.value?.resource_data?.length;

      await StoreScriptData(info).finally(() => {
        loading.value = false;
      });
    };

    // 模板新建后的弹窗提示
    const closeModelState = (type) => {
      console.log(addTemplateNextDialog.value, "addTemplateNextDialog");
      loading.value = true;
      addTemplateNextDialog.value && addTemplateNextDialog.value.closeModal();
      if (type == "back") {
        // 返回模板广场
        router.push(
          `/workShotstack/materialCenter/TemplateList?templateType=${
            queryData.value?.templateType || ""
          }`
        );
      }
    };

    // 智能生图抽屉组件点击确定, 修改模板的数据 modelId:选择的ai配图id
    const getAiCreateTemplateData = async (modelId) => {
      state.tipText = " AI 数据导入中...";
      loading.value = true;
      const queryParams = {
        id: queryData.value.id,
        unique_id: queryData.value.unique_id,
        is_polling: 1, // 开启轮询
      };
      // 修改当前选择的模型类型
      changeChecked(modelId);
      try {
        // 修改 ai配图当前选择的模型id
        const getDetaile = async () => {
          const res = await request.get(
            "/work_ai",
            "/user/shotstack/inspirationText/record/detail",
            queryParams
          );

          if (res?.code && res?.code != 1000) {
            throw new Error(res?.msg);
          }

          console.log(res, "ai生成结果");
          if (res.result?.polling_status == "doing") {
            setTimeout(() => {
              getDetaile();
            }, 2500);
            return;
          }
          processingData(res);
        };
        await getDetaile();
      } catch (error) {
        // message.error("获取详情失败!");
        Modal.info({
          title: "提示",
          okText: "返回",
          keyboard: false,
          content: h("div", {}, [h("p", "获取详情失败!")]),
          onOk() {
            // router.push(
            //   `/workShotstack/materialCenter/TemplateList?templateType=${
            //     queryData.value?.templateType || "0"
            //   }`
            // );
            router.back();
          },
        });
      }
    };

    // 修改ai生图中默认选中的项,
    const changeChecked = (id) => {
      const find = state.aiModelList.find((ele) => ele.selected == 1);
      if (find?.id && find.id != id) {
        find.selected = 0;
        state.aiModelList.forEach((ele) => {
          ele.id == id && (ele.selected = 1);
        });
      } else {
        state.aiModelList.forEach((ele) => {
          ele.id == id && (ele.selected = 1);
        });
      }
    };

    // 打开的方式, 新增或者替换
    const getVoiceType = ref(null);
    // 字幕与配音打开素材库
    const openUpLoad = (type = "add") => {
      getVoiceType.value = type;
      addVisible.value = true;
    };

    // template ai生成图片 是否运行轮询
    const TemplateAiCreatSwitch = computed({
      get() {
        return store.state.shotstack.TemplateAiCreatSwitch;
      },
      set(val) {
        store.commit("SET_TemplateAiCreatSwitch_SWITCH", val);
      },
    });

    onUnmounted(() => {
      // 清除定时器
      timerId.value && clearInterval(timerId.value);
      // 如果有ai生成的, 关闭轮询的开关
      TemplateAiCreatSwitch.value = false;
      window.removeEventListener("beforeunload", setupBeforeUnloadListener);
      Modal.destroyAll();
      loading.value = false;
    });

    watch(
      () => store.state.user?.clipRole,
      (val) => {
        if (val) {
          state.clipRole = val;
        } else {
          state.clipRole = [];
        }
      },
      {
        deep: true,
        immediate: true,
      }
    );

    return {
      ...toRefs(state),
      updateName,
      initMediaList,
      getGroupName,
      changeChecked,
      groupCount,
      title_name,
      ai_requestData,
      getVoiceType,
      TemplateAiCreatSwitch,
      openUpLoad,
      backClick,
      closeModelState,
      closeGobackModal,
      showGobackModal,
      authoringScriptHandle,
      AIWritingAssistantHandle,
      openSubtitledubbingDrawer,
      openSettitleDrawer,
      previewHandle,
      addVideoGroupHandle,
      scrollToBottom,
      guideHandle,
      saveTemplateHandle,
      openGlobalT,
      GlobTitleState,
      openGlobalSubtitledubbingDrawer,
      setupBeforeUnloadListener,
      closeChooseMaterial,
      getAiMod,
      openAicreateImg,
      AiCreateImg_DrawerRef,
      processingData,
      getAiCreateTemplateData,
      manualCreation,
      addTemplateNextDialog,
      // PlotDialogRef,
      isShowTitleBtn,
      addVisible,
      GloballedubbingDrawer,
      subtitledubbingDrawer,
      literalTitleDrawerComponent,
      queryData,
      VideoMashup,
      titleText,
      loading,
      ai_mapping,
      timerId,
      globalLabel,
      globalSubtitledubbingDrawer,
      allVideoGroup,
      paramsData,
      AiCreateImgRef,
      importScript,
    };
  },
});
</script>

<style lang="less" scoped>
.container {
  height: 100vh;
  width: 100%;
  overflow: hidden;
  // display: flex;
  // flex-direction: column;

  // 头部左侧样式
  .right_btns {
    font-size: 14px;
    display: flex;
    gap: 10px;

    .guide_box {
      color: #4e5969;
      display: flex;
      align-items: center;
      cursor: pointer;

      span {
        margin-left: 6px;
      }
    }
  }

  .content {
    // background-color: #2d66bb;
    height: calc(100% - 64px);

    .content-box {
      display: flex;
      height: 100%;
      overflow: hidden;

      .content-lf {
        flex: 1;
        // padding: 20px;
        display: flex;
        flex-direction: column;
        min-width: 650px;
        border-right: 1px solid #f3f3f3;

        .content-lf-header {
          padding: 24px 32px;
          height: 98px;
          display: flex;
          align-items: center;
          justify-content: space-between;
        }

        .lf-header-btn-group {
          display: flex;
          justify-content: space-between;
          align-items: center;
          height: 40px;
          gap: 10px;

          .ai_plot {
            margin-right: 15px;
            display: flex;
            gap: 5px;

            .trigger_span {
              cursor: pointer;
            }
          }
        }

        .videoGroupCard_box {
          flex: 1;
          overflow-y: scroll;
          padding: 0 32px;

          &::-webkit-scrollbar {
            width: 8px;
            /* 滚动条的宽度 */
            height: 10px;
            /* 滚动条的高度，垂直滚动条可能用得上 */
          }

          &::-webkit-scrollbar-thumb {
            background: #cecece;
            /* 滑块的背景颜色 */
            border-radius: 10px;
            /* 滑块的圆角 */
          }

          .tongs {
            cursor: grab;
            display: inline-block;
            transform: translate(-20px, 20px);
            // float: left;
            position: absolute;
            left: 23px;
            top: 12px;

            &:hover {
              background-color: #f1f1f1;
            }
          }
        }
      }

      .content-middle {
        padding: 24px 28px 24px 32px;
        width: 350px;
        min-width: 350px;

        .content-middle-context {
          width: 100%;
          margin-top: 30px;
        }
      }

      .content-rg {
        min-width: 350px;
        padding: 24px 28px 24px 32px;
        height: 100%;
        background: #f6f8fa;

        .content-rg-context {
          height: 100%;
        }
      }
    }
  }
}
</style>
